/*
 * @Copyright (c) 2018 缪聪(mcg-helper@qq.com)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");  
 * you may not use this file except in compliance with the License.  
 * You may obtain a copy of the License at  
 *     
 *     http://www.apache.org/licenses/LICENSE-2.0  
 *     
 * Unless required by applicable law or agreed to in writing, software  
 * distributed under the License is distributed on an "AS IS" BASIS,  
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
 * See the License for the specific language governing permissions and  
 * limitations under the License.
 */

package com.mcgrobot.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.mcgrobot.common.Constants;
import com.mcgrobot.controller.base.BaseController;
import com.mcgrobot.entity.auth.McgUser;
import com.mcgrobot.entity.auth.PermissionCollection;
import com.mcgrobot.entity.auth.UserCacheBean;
import com.mcgrobot.entity.common.McgResult;
import com.mcgrobot.plugin.endesign.RSAEncrypt;
import com.mcgrobot.service.UserService;

/**
 * 
 * @ClassName:   LoginController   
 * @Description: TODO(负责登录和登出) 
 * @author:      缪聪(mcg-helper@qq.com)
 * @date:        2018年3月9日 下午5:24:29  
 *
 */
@Controller
public class LoginController extends BaseController {
	
	private static Logger logger = LoggerFactory.getLogger(LoginController.class);
	@Autowired
	private UserService userService;
	
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView login(HttpServletRequest reuqest, HttpServletResponse response, RedirectAttributes attributes) {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("redirect:/login.jsp");
        
        if(reuqest.getHeader("x-requested-with")!=null && reuqest.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){
            mv.setViewName("timeout");
        } else {
        	
        	String account = reuqest.getParameter("account");
        	String pwd = reuqest.getParameter("pwd");
        	if(!StringUtils.isEmpty(account) && !StringUtils.isEmpty(pwd)  ) {
        		try {
        			
        			McgUser mcgUser = userService.selectByPrimaryKey(account);
        			if(mcgUser != null) {
        				if(mcgUser.getPwd().equals(DigestUtils.md5DigestAsHex(RSAEncrypt.segmentDecrypt(pwd).getBytes(Constants.CHARSET)))) {
        	        		UserCacheBean ucb = new UserCacheBean();
        	                ucb.setSessionID(reuqest.getSession().getId());
        	                mcgUser.setLastLoginTime(new Date());
        	                ucb.setUser(mcgUser);
        	                PermissionCollection.getInstance().addSessionUserCache(reuqest.getSession().getId(), ucb);
        	                reuqest.getSession().setMaxInactiveInterval(Constants.HTTP_SESSION_TIME_OUT);
        	                
        	                mv.setViewName("redirect:/index");
        				} else {
        					mv.addObject("message", "密码输入错误！");
        				}
        			} else {
        				mv.addObject("message", "该用户不存在！");
        			}
	        		
        		} catch (Exception e){
        			logger.error("用户名{}，登录出现异常：", account, e);
        		}
        		
        	} else {
        		mv.addObject("message", "请填写用户和密码！");
        	}


            return mv;
        }

        return mv;
    }
    
    @RequestMapping(value = "/loginOut", method = RequestMethod.POST)
    @ResponseBody
    public McgResult loginOut(HttpSession session) {
    	McgResult mcgResult = new McgResult();
    	try {
    		PermissionCollection.getInstance().removeSessionUserCache(session.getId());
    	} catch(Exception e) {
    		logger.error("退出登录出错：", e);
    		mcgResult.setStatusCode(0);
    	}
    	return mcgResult;
    }

}
